package com.jackrain.nea.shiro.stateful;

import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.util.ShiroSessionUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * Created by Lucky dog on 2016/7/26.
 */
public class RetryLimitCredentialsMatcher extends SimpleCredentialsMatcher {

    private static Logger logger= LoggerFactory.getLogger(RetryLimitCredentialsMatcher.class.getName());


    @Value("${raincloud.session.max-active}")
    private int maxSession;
    @Autowired
    private RedisOpsUtil<String,String> redisOpsUtil;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        ValueHolder vh = new ValueHolder();
        String username = (String) token.getPrincipal();
        User user = info.getPrincipals().oneByType(User.class);

        if(user.getFailedLoginAttempts() > 10){
            vh.put("code",-1);
            vh.put("message", "用户名为:【" + username + "】的用户登录失败次数过多");
            ShiroSessionUtil.setAttribute("vh",vh);
            return false;
        }
        boolean matches = super.doCredentialsMatch(token, info);
        int count;
        if(matches){
            Object o = redisOpsUtil.strRedisTemplate.opsForValue().get("usercnt:"+user.getName());
            count = (o == null) ? 0 : Integer.parseInt(o.toString());
            if(maxSession > 0 && count > maxSession+1){
                vh.put("code",-1);
                vh.put("message", "当前已达到最大并发人数");
                ShiroSessionUtil.setAttribute("vh",vh);
                return false;
            }
        }else{
            vh.put("code",-1);
            vh.put("message", "密码不正确");
            ShiroSessionUtil.setAttribute("vh",vh);
            return false;
        }

        return matches;
    }

}
